import json

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from books.models import BookInfo


# Create your views here.
class BooksView(View):

    def get(self, request):
        """
            获取所有图书
        :param request:
        :return:
        """

        # 查询所有图书数据
        books = BookInfo.objects.all()

        # 构造返回数据
        book_list = []
        for book in books:
            book_list.append({
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment
            })

        return JsonResponse({'book_list': book_list})

    def post(self, request):
        """
            保存图书操作
        :param request:
        :return:
        """

        # 1、获取数据 json 根据接口中规定的不同的数据形式进行获取
        data_json = request.body.decode()
        # 1-1 将json转化为字典
        data_dict = json.loads(data_json)
        # 1-2 提取字段数据
        btitle = data_dict.get('btitle')
        bpub_date = data_dict.get('bpub_date')
        # 2、验证数据
        # 2-1 验证数据完整性
        if not all([btitle, bpub_date]):
            return JsonResponse({'error': '缺失数据'}, status=400)
        # 2-2 验证书名的长度
        if len(btitle) < 1 or len(btitle) > 20:
            return JsonResponse({'error': '书名长度不符合'}, status=400)

        # 3、保存数据
        # BookInfo.objects.create(btitle=btitle,bpub_date=bpub_date)
        book = BookInfo.objects.create(**data_dict)
        # 4、返回结果
        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment
        })


class BookView(View):

    def get(self, request, pk):
        """
            获取一本图书
        :param request:
        :return:
        :pk: 图书id数据
        """
        # 1、根据图书id获取图书
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '图书不存在'})
        # 2、返回图书数据
        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment
        })

    def put(self, request, pk):
        """
            更新一本图书
        :param request:
        :param pk:
        :return:
        """
        # 1、根据id获取要更新的图书对象
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '图书不存在'})
        # 2、获取更新的字段数据
        data_json = request.body.decode()
        # 2-1 将json转化为字典
        data_dict = json.loads(data_json)
        # 2-2 提取字段数据
        btitle = data_dict.get('btitle')
        bpub_date = data_dict.get('bpub_date')
        # 3、验证数据
        # 验证书名的长度
        if btitle:
            if len(btitle) < 1 or len(btitle) > 20:
                return JsonResponse({'error': '书名长度不符合'}, status=400)
        # 4、更新字段
        if btitle:
            book.btitle = btitle
        if bpub_date:
            book.bpub_date = bpub_date
        book.save()

        # 5、返回数据
        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment
        })

    def delete(self, request, pk):
        """
            删除一本图书
        :param request:
        :param pk:
        :return:
        """
        # 1、获取删除的图书对象
        try:
            book = BookInfo.objects.get(id=pk)
        except:
            return JsonResponse({'error': '图书不存在'})
        # 2、删除图书  物理删除 逻辑删除
        # book.delete()  # 物理删除
        book.is_delete = True
        book.save()
        # 3、返回结果
        return JsonResponse({})
